package com.piggy.logi.sys.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import com.piggy.common.core.constant.SecurityConstants;
import com.piggy.common.core.domain.R;
import com.piggy.common.core.utils.PageUtils;
import com.piggy.common.core.web.page.TableDataInfo;
import com.piggy.common.satoken.utils.SecurityUtils;
import com.piggy.logi.sys.api.utils.ZhongYouApiUtil;
import com.piggy.logi.sys.bo.LogiWaybillSignEditBo;
import com.piggy.logi.sys.bo.LogiWaybillSignQueryBo;
import com.piggy.logi.sys.bo.OperationReceiptBo;
import com.piggy.logi.sys.domain.LogiGoodOrder;
import com.piggy.logi.sys.domain.LogiWaybill;
import com.piggy.logi.sys.domain.LogiWaybillOrderRelate;
import com.piggy.logi.sys.domain.LogiWaybillSign;
import com.piggy.logi.sys.enums.WaybillStatusEnum;
import com.piggy.logi.sys.mapper.LogiWaybillSignMapper;
import com.piggy.logi.sys.service.ILogiGoodOrderService;
import com.piggy.logi.sys.service.ILogiWaybillOrderRelateService;
import com.piggy.logi.sys.service.ILogiWaybillService;
import com.piggy.logi.sys.service.ILogiWaybillSignService;
import com.piggy.logi.sys.vo.LogiWaybillSignVo;
import com.piggy.sys.api.RemoteOssService;
import com.piggy.sys.api.vo.SysOssVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;

/**
 * 运单签收Service业务层处理
 *
 * @author piggy
 * @date 2023-09-19
 */
@Slf4j
@Service
public class LogiWaybillSignServiceImpl extends ServiceImpl<LogiWaybillSignMapper, LogiWaybillSign> implements ILogiWaybillSignService {

    @Resource
    private ILogiWaybillService waybillService;

    @Resource
    private ILogiWaybillOrderRelateService waybillOrderRelateService;

    @Resource
    private ILogiGoodOrderService logiGoodOrderService;

    @Resource
    private RemoteOssService remoteOssService;

    @Override
    public LogiWaybillSignVo queryById(Long signedId) {
        return getVoById(signedId, LogiWaybillSignVo.class);
    }

    @Override
    public TableDataInfo<LogiWaybillSignVo> queryPageList(LogiWaybillSignQueryBo bo) {
        bo.setDeptId(SecurityUtils.getDeptId());
        PageInfo<LogiWaybillSignVo> result = startPage(bo).doSelectPageInfo(() -> {
            List<LogiWaybillSignVo> voList = baseMapper.selectSignList(buildQueryWrapper(bo));
        });
        return PageUtils.buildDataInfo(result);
    }

    @Override
    public List<LogiWaybillSignVo> queryList(LogiWaybillSignQueryBo bo) {
        bo.setDeptId(SecurityUtils.getDeptId());
        return baseMapper.selectSignList(buildQueryWrapper(bo));
    }

    private QueryWrapper<LogiWaybillSign> buildQueryWrapper(LogiWaybillSignQueryBo bo) {
        QueryWrapper<LogiWaybillSign> lqw = Wrappers.query();
        lqw.eq(bo.getDeptId() != null, "sign.dept_id", bo.getDeptId());
        lqw.eq(bo.getWaybillId() != null, "bill.waybill_id", bo.getWaybillId());
        lqw.like(StrUtil.isNotBlank(bo.getSigner()), "bill.signer", bo.getSigner());
        lqw.like(StrUtil.isNotBlank(bo.getSignedPhone()), "bill.signed_phone", bo.getSignedPhone());
        lqw.eq(bo.getSignedStatus() != null, "bill.signed_status", bo.getSignedStatus());
        lqw.like(StrUtil.isNotBlank(bo.getSignedIdcard()), "bill.signed_idcard", bo.getSignedIdcard());
        lqw.eq(bo.getSignedType() != null, "bill.signed_type", bo.getSignedType());
        lqw.eq(bo.getSignedAgentFlag() != null, "bill.signed_agent_flag", bo.getSignedAgentFlag());
        lqw.like(StrUtil.isNotBlank(bo.getSignedRemark()), "bill.signed_remark", bo.getSignedRemark());
        lqw.in(CollUtil.isNotEmpty(bo.getWaybillIds()), "bill.waybill_id", bo.getWaybillIds());
        lqw.and(StrUtil.isNotBlank(bo.getCustomerName()), lqw1 -> lqw1.like("c1.customer_name", bo.getCustomerName()).or().like("c2.customer_name", bo.getCustomerName()));
        lqw.eq("sign.del_flag", "0");
        return lqw;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public LogiWaybillSignVo insertByAddBo(LogiWaybillSignEditBo bo) {
        LogiWaybillSign add = BeanUtil.toBean(bo, LogiWaybillSign.class);
        save(add);
        // 处理回单附件
        if (StrUtil.isNotBlank(bo.getSignedAttach())) {
            waybillService.receipt(new OperationReceiptBo()
                    .setReceiptAttachments(bo.getSignedAttach())
                    .setWaybillId(bo.getWaybillId()));
        }

        if (add.getSignedStatus() == 0) {
            waybillService.updateStatus(add.getWaybillId(), WaybillStatusEnum.ARRIVAL.getCode());
        }
        if (add.getSignedStatus() == 1) {
            waybillService.updateStatus(add.getWaybillId(), WaybillStatusEnum.SIGNATURE.getCode());
            // 通知众油平台
            List<LogiWaybillOrderRelate> waybillOrderRelateList = waybillOrderRelateService.listByWaybillIds(CollUtil.newArrayList(add.getWaybillId()));
            for (LogiWaybillOrderRelate logiWaybillOrderRelate : waybillOrderRelateList) {
                if (logiWaybillOrderRelate.getGoodOrderType() == 1) {
                    LogiGoodOrder goodOrder = logiGoodOrderService.getById(logiWaybillOrderRelate.getGoodOrderId());
                    LogiWaybill waybill = waybillService.getById(logiWaybillOrderRelate.getWaybillId());
                    // 获取回单
                    String type1 = null, image1 = null, type2 = null, image2 = null;
                    if (StrUtil.isNotBlank(waybill.getOutboundAttach())) {
                        try {
                            if (waybill.getOutboundAttach().contains(",")) {
                                String[] outboundAttachs = waybill.getOutboundAttach().split(",");
                                R<SysOssVo> ossVo = remoteOssService.getSysOssById(outboundAttachs[0], SecurityConstants.INNER);
                                SysOssVo vo = ossVo.getData();
                                type1 = vo.getFileType();
                                image1 = Base64Encoder.encode(HttpUtil.downloadBytes(vo.getUrl()));
                                ossVo = remoteOssService.getSysOssById(outboundAttachs[1], SecurityConstants.INNER);
                                vo = ossVo.getData();
                                type2 = vo.getFileType();
                                image2 = Base64Encoder.encode(HttpUtil.downloadBytes(vo.getUrl()));
                            } else {
                                R<SysOssVo> ossVo = remoteOssService.getSysOssById(waybill.getOutboundAttach(), SecurityConstants.INNER);
                                SysOssVo vo = ossVo.getData();
                                type1 = vo.getFileType();
                                image1 = Base64Encoder.encode(HttpUtil.downloadBytes(vo.getUrl()));
                            }
                        } catch (Exception e) {
                            log.error("获取base64回单图片失败：" + e);
                        }
                    }
                    ZhongYouApiUtil.orderFinish(goodOrder.getPickupOrderNo(), logiWaybillOrderRelate.getWaybillId().toString(), DateUtil.now(), type1, image1, type2, image2);
                }
            }
        }
        return queryById(add.getSignedId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public LogiWaybillSignVo updateByEditBo(LogiWaybillSignEditBo bo) {
        LogiWaybillSign update = BeanUtil.toBean(bo, LogiWaybillSign.class);
        updateById(update);
        // 处理回单附件
        if (StrUtil.isNotBlank(bo.getSignedAttach())) {
            waybillService.receipt(new OperationReceiptBo()
                    .setReceiptAttachments(bo.getSignedAttach())
                    .setWaybillId(bo.getWaybillId()));
        }

        LogiWaybillSignVo vo = queryById(update.getSignedId());
        if (vo.getSignedStatus() == 0) {
            waybillService.updateStatus(vo.getWaybillId(), WaybillStatusEnum.ARRIVAL.getCode());
        }
        if (vo.getSignedStatus() == 1) {
            waybillService.updateStatus(vo.getWaybillId(), WaybillStatusEnum.SIGNATURE.getCode());
        }
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        if (CollUtil.isNotEmpty(ids)) {
            ids.forEach(t -> waybillService.updateStatus(getById(t).getWaybillId(), WaybillStatusEnum.ARRIVAL.getCode()));
        }
        return removeByIds(ids);
    }
}
